package com.vonchenchen.mytest.RollLoadPhotoView;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.RelativeLayout;
import android.widget.Toast;

/**
 * Created by vonchenchen on 2015/10/28 0028.
 */
public class ScaleRelativeLayout extends RelativeLayout{

    private Context mCtx;

    /** 边长缩放 */
    private final int SCALE_ADD = 30;
    /** 临界刷新拉动距离 */
    private final int DISTANCE_FRASH = 150;

    public final int STATUS_NORMAL = 0;
    //有拉动                             松手复位
    public final int STATUS_PULL = 1;
    public final int STATUS_LOAD_LEFT = 2;
    public final int STATUS_LOAD_RIGHT = 3;
    //进入Load状态后又返回拉动          松手复位
    public final int STATUS_RETURN_PULL = 4;

    private OnDismissListener mDismissListener;

    private boolean mFirstLayoutFlag = true;
    private boolean mFirstMoveFlag = true;
    private int mCurrentStatus;

    private boolean isTop;

    private int mDownX;
    private int mMoveX;

    private int mDownY;
    private int mMoveY;

    private int mOriginalHeight;
    private int mOriginalWidth;

    private float mRecorderX;
    private float mRecorderY;

    public int mRecordLeft;
    public int mRecordTop;
    public int mRecordRight;
    public int mRecordBotton;

    private int mScreenWidth;
    private int mScreenHeight;

    //旋转角度记录
    private float mRecordRotation;

    //标准位置参考控件的id
    private int mStandardLocationViewId;

    public ScaleRelativeLayout(Context context) {
        super(context);
        mCtx = context;
        init();
    }

    public ScaleRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mCtx = context;
        init();
    }

    private void init(){
        isTop = false;
        mCurrentStatus = STATUS_NORMAL;
        mScreenWidth = getScreenWidth((Activity)mCtx);
        mScreenHeight = getScreenHeight((Activity)mCtx);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        initSize();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);

        if(mFirstLayoutFlag) {
            mRecordLeft = l;
            mRecordTop = t;
            mRecordRight = r;
            mRecordBotton = b;

            mFirstLayoutFlag = false;
        }

        if(mCurrentStatus == STATUS_PULL || mCurrentStatus == STATUS_RETURN_PULL){

        }
    }

    private void initSize(){
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) this.getLayoutParams();
        mOriginalHeight = params.height;
        mOriginalWidth = params.width;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if(isTop) {
            int action = event.getAction();
            //Toast.makeText(mCtx,"haha",Toast.LENGTH_SHORT).show();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    mDownX = (int) event.getRawX();
                    mDownY = (int) event.getRawY();

                    setOnDownLayoutStat();
                    mRecorderX = 0;
                    mRecorderY = 0;
                    mFirstMoveFlag = true;

                    break;
                case MotionEvent.ACTION_MOVE:

                    if(mFirstMoveFlag && Math.abs(mMoveX - mDownX)>DISTANCE_FRASH){
                        setScaleBigger();
                        mFirstMoveFlag = false;
                    }

                    mMoveX = (int) event.getRawX();
                    mMoveY = (int) event.getRawY();
                    Log.i("ScaleRelativeLayout", "mMoveX   " + mMoveX + "  mDownX  " + "mMoveX - mDownX" + (mMoveX - mDownX));
                    setOnMoveLayoutStat(mMoveX - mDownX, mMoveY - mDownY);
                    break;
                case MotionEvent.ACTION_UP:

                    setOnUpLayoutStat();

                    mCurrentStatus = STATUS_NORMAL;
                    break;
            }

            super.onTouchEvent(event);
            return true;
        }else{
            return super.onTouchEvent(event);
        }
    }

    private void setOnMoveLayoutStat(int distanceX, int distanceY){

        //角度
        float rotation = distanceX / 12;
        mRecordRotation = rotation;
        ScaleRelativeLayout.this.setRotation(rotation);

        if(Math.abs(distanceX) > DISTANCE_FRASH) {

            if(distanceX < 0) {
                mCurrentStatus = STATUS_LOAD_LEFT;
            }else if(distanceX > 0){
                mCurrentStatus = STATUS_LOAD_RIGHT;
            }
        }else if(mCurrentStatus == STATUS_LOAD_LEFT || mCurrentStatus == STATUS_LOAD_RIGHT){
            mCurrentStatus = STATUS_RETURN_PULL;
        }

        if(mCurrentStatus != STATUS_PULL){
            RelativeLayout.LayoutParams params = (LayoutParams) this.getLayoutParams();
            int length = Math.abs(distanceY);
            this.setLayoutParams(params);
            float deltaX = (float) (distanceX * 1);
            float deltaY = (float) (distanceY * 1);
            mRecorderX = deltaX;
            mRecorderY = deltaY;

            this.setTranslationX(deltaX);
            this.setTranslationY(deltaY);
        }
    }

    private void setOnDownLayoutStat(){

        mCurrentStatus = STATUS_PULL;
    }

    private void setScaleBigger(){
        //大小缩放
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) this.getLayoutParams();
        params.height = mOriginalHeight+SCALE_ADD;
        params.width = mOriginalWidth+SCALE_ADD;
        this.setLayoutParams(params);
    }

    private void setOnUpLayoutStat(){

        RelativeLayout.LayoutParams params = (LayoutParams) this.getLayoutParams();

        if(mCurrentStatus == STATUS_LOAD_LEFT){
            //Toast.makeText(mCtx,"LOAD_LEFT",Toast.LENGTH_SHORT).show();
            dissmissAnimator(this, 0);
        }else if(mCurrentStatus == STATUS_LOAD_RIGHT){
            //Toast.makeText(mCtx,"LOAD_RIGHT",Toast.LENGTH_SHORT).show();
            dissmissAnimator(this, 1);
        }
        //控件归位
        else if(mCurrentStatus == STATUS_PULL || mCurrentStatus == STATUS_RETURN_PULL){

            reductionAnimator(this);
        }

        if(mFirstMoveFlag == false) { //如果之前有过放大，现在缩小
            params.height = params.height - SCALE_ADD;
            params.width = mOriginalWidth - SCALE_ADD;
        }
        //params.addRule(RelativeLayout.CENTER_IN_PARENT);
        this.setLayoutParams(params);
    }

    /**
     * 图片切换时需要的操作
     * @param view
     * @param opt    1 左    2 右
     */
    private void dissmissAnimator(final View view, final int opt){
        final ValueAnimator animator = ValueAnimator.ofInt(0, dip2px(mCtx, 600));
        animator.setDuration(200);
        animator.setInterpolator(new LinearInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {

                Integer integer = (Integer) animator.getAnimatedValue();
                float x;
                if (opt == 0) {    //左
                    x = mRecorderX - integer;
                    view.setTranslationX(x);
                } else {
                    x = mRecorderX + integer;
                    view.setTranslationX(mRecorderX + integer);
                }
                view.setRotation(x / 12);
                view.setTranslationY(mRecorderY + integer);
            }
        });

        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                //还原角度
                ScaleRelativeLayout.this.setRotation(0);
                //清空位置数据
                mRecorderX = 0;
                mRecorderY = 0;
                //控件归位
                ScaleRelativeLayout.this.setTranslationX(0);
                ScaleRelativeLayout.this.setTranslationY(0);
                //进行回调
                if(mDismissListener != null){
                    if(opt == 0){
                        mDismissListener.onLeftDismiss(view);
                    }else if(opt == 1){
                        mDismissListener.onRightDismiss(view);
                    }
                }
            }
            @Override
            public void onAnimationCancel(Animator animation) {
            }
            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
        animator.start();
    }

    /**
     * 图片还原时需要的操作
     * @param view
     */
    private void reductionAnimator(final View view){

        if(mRecordRotation < 1){    //角度为0时无法执行动画结束回调,强行赋值1
            mRecordRotation = 1;
        }
        final ValueAnimator animator = ValueAnimator.ofFloat(mRecordRotation, 0);
        animator.setDuration(100);
        animator.setInterpolator(new LinearInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float data = (float) animator.getAnimatedValue();
                view.setRotation(data);

                float k = data / mRecordRotation;
                float x = mRecorderX * k;
                float y = mRecorderY * k;

                view.setTranslationX(x);
                view.setTranslationY(y);
            }
        });

        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mRecorderX = 0;
                mRecorderY = 0;
                if(mDismissListener != null){
                    mDismissListener.onReduction(view);
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });

        animator.start();
    }

    public int getmCurrentStatus(){
        return mCurrentStatus;
    }

    public void setIsTop(boolean bool){
        isTop = bool;
    }

    public  boolean getIsTop(){
        return isTop;
    }

    public void getStandardLocationViewId(int rId){
        mStandardLocationViewId = rId;
    }

    public int getScreenWidth(Activity activity) {
        return activity.getWindowManager().getDefaultDisplay().getWidth();
    }

    public int getScreenHeight(Activity activity) {
        return activity.getWindowManager().getDefaultDisplay().getHeight();
    }

    public int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale);
    }

    public void setOnDismissListener(OnDismissListener dismissListener){
        this.mDismissListener = dismissListener;
    }

    /**
     * 监听消失
     */
    public interface OnDismissListener{
        public void onLeftDismiss(View view);
        public void onRightDismiss(View view);
        public void onReduction(View view);
    }
}
